package com.ziroom.crm.mq.core.resend;

import com.ziroom.crm.mq.core.config.MqConfig;
import com.ziroom.crm.mq.core.init.InitFunc;
import lombok.extern.slf4j.Slf4j;

/**
 * <p></p>
 * <p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author WeiShaoying
 * @version 1.0
 * @date Created in 2020年09月03日 16:25
 * @since 1.0
 */
@Slf4j
@SuppressWarnings("ALL")
public class ReSendInitFunc implements InitFunc {

    /**
     * 休眠时间
     */
    private static final int DEFAULT_SLEEP_TIME = 5 * 60 * 1000;

    /**
     * 重试消息
     *
     * @throws Exception
     */
    @Override
    public void init() throws Exception {
        //判断是否开启内部定时
        log.info("ReSendInitFunc innerJob={}", MqConfig.getConfig(MqConfig.INNER_JOB_ENABLE));
        if (!MqConfig.getConfig(MqConfig.INNER_JOB_ENABLE).equals(Boolean.FALSE.toString())) {
            Task task = new Task();
            Thread thread = new Thread(task);
            //开启守护线程 不影响系统关闭
            thread.setDaemon(true);
            thread.start();
        }
    }

    private static class Task implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    ReSendInvoker.resend();
                    //log.debug("ReSendInitFunc Sleep={}毫秒", getSleepMilli());
                    Thread.sleep(getSleepMilli());
                } catch (InterruptedException e) {
                    log.error("[rock-mq] Resend sleep fail or run fail", e);
                }
            }
        }
    }

    public static int getSleepMilli() {
        return MqConfig.getConfigInt(MqConfig.RESEND_THREAD_SLEEP_MILLI, DEFAULT_SLEEP_TIME);
    }

}
